<?php

class Request {

	private static $source = false;
	private static $xml = false;
	private static $simulated_params = false;

	static function init ()
	{
		if (self::$source != 0) return;
			
		// trying to load request code from POST
		self::$source = @$_POST['query'];
		if (!self::$source)
		{
			if (key_exists('query_type', $_GET))
			{
				self::$source['id'] = @$_GET['query_id'];
				self::$source['type'] = ($_GET['query_type']) ? $_GET['query_type'] : 'HTML';
				self::$source['param'] = array_merge($_POST, $_GET);
				return true;
			} elseif (key_exists('query_type', $_POST)) {
				self::$source['id'] = $_POST['query_id'];
				self::$source['type'] = ($_POST['query_type']) ? $_POST['query_type'] : 'HTML';
				self::$source['param'] = array_merge($_POST, $_GET);
				return true;
			}
			self::$source['id'] = 0;
			self::$source['type'] = 'HTML';
			self::$source['param'] = array();
		}
			
		if (!is_array(self::$source)) self::$xml = simplexml_load_string(self::$source);
	}

	static function id()
	{
		if (self::$simulated_params !== false)
		{
			return self::$simulated_params['id'];
		}
		if(!self::$xml) return self::$source['id'];
		else return self::$xml['id'];
	}

	static function type()
	{
		if (self::$simulated_params != false)
		{
			return self::$simulated_params['type'];
		}
		if(!self::$xml) return strtoupper(self::$source['type']);
		else return strtoupper(self::$xml->type);
	}

	static function param($name)
	{
		if (self::$simulated_params !== false)
		{
			return addslashes(self::$simulated_params[$name]);
		}
		if(!self::$xml) return addslashes(@self::$source['param'][$name]);
		else return (string) addslashes(self::$xml->xpath("//param[@name='$name']"));
	}


	static function simulate($params)
	{
		Log::put('Simulation started...');
		if (self::$simulated_params !== false) {
			Log::fatal('Unable to start Request simulation: already started.', QConst::X_SIMULATION_FAILED);
		}
		self::$simulated_params = $params;
	}

	function simulating()
	{
		return (false || !self::$simulated_params);
	}

	function unsimulate()
	{
		self::$simulated_params = false;
	}
}

Request::init();
?>